/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.GiveawayDao;
import com.hboxs.asl.entity.Giveaway;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

/**
 * Dao - 企业服务
 */
@Repository("giveawayDaoImpl")
public class GiveawayDaoImpl extends BaseDaoImpl<Giveaway, Long> implements GiveawayDao {

    @Override
    public List<Giveaway> findValid() {
        String queryStr = "SELECT giveaway FROM Giveaway AS giveaway " +
                "WHERE " +
                "   (current_date BETWEEN giveaway.startDate AND giveaway.endDate ) OR " +
                "   (giveaway.endDate is null AND current_date >= giveaway.startDate) ";
        return entityManager.createQuery(queryStr).getResultList();
    }

    @Override
    public Giveaway find(BigDecimal quota) {
        String jpql = "SELECT giveaway FROM Giveaway AS giveaway " +
                "WHERE giveaway.quota<=:quota " +
                "ORDER BY giveaway.quota DESC";
        List<Giveaway> giveaways = entityManager.createQuery(jpql).setParameter("quota", quota).getResultList();
        if (giveaways.size() == 0) {
            return null;
        } else {
            return giveaways.get(0);
        }
    }
}
